<?php

namespace app\api\controller;

use app\common\controller\Api;
use Carbon\Carbon;
use think\Exception;

/**
 * 首页接口
 */
class Coupon extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function list()
    {
        $userId = $this->auth->getUser()->id;
        $coupons = \app\admin\model\Coupon::where('status', 1)->order('id', 'desc')->select();

        $userCoupons = \app\admin\model\user\Coupon::where('user_id', $userId)->field('coupon_id')->select();
        $userCouponIds = [];
        foreach ($userCoupons as $v) {
            $userCouponIds[] = $v->coupon_id;
        }

        $coupons = array_map(function ($e) use ($userCouponIds) {
            if (in_array($e->id, $userCouponIds)) {
                $e['is_owned'] = 1;
            } else {
                $e['is_owned'] = 0;
            }
            return $e;
        }, $coupons);

        $this->success('ok', $coupons);
    }

    public function takecoupon()
    {
        $userId = $this->auth->getUser()->id;
        $couponId = $this->request->post('couponid');

        $coupon = \app\admin\model\Coupon::where('id', $couponId)->find();
        if (!$coupon) {
            $this->error('领取失败');
        }
        try {
            \app\admin\model\user\Coupon::create([
                'user_id' => $userId,
                'coupon_id' => $coupon->id,
                'coupon_name' => $coupon->coupon_name,
                'coupon_type' => $coupon->coupon_type,
                'reduce_price' => $coupon->reduce_price,
                'discount' => $coupon->discount,
                'min_price' => $coupon->min_price,
                'start_time' => (function ($coupon) {
                    if (2 == $coupon->expire_type) {
                        return $coupon->start_time;
                    } else if (1 == $coupon->expire_type) {
                        return Carbon::now()->toDateString();
                    }
                })($coupon),
                'end_time' => (function ($coupon) {
                    if (2 == $coupon->expire_type) {
                        return $coupon->end_time;
                    } else if (1 == $coupon->expire_type) {
                        return Carbon::now()->addDays($coupon->expire_day)->toDateString();
                    }
                })($coupon),
                'store_id' => $coupon->store_id,
                'room_id' => $coupon->room_id,
            ]);

            $this->success('领取成功');

        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }
}
